//
//  BSLGalleryPlugin.m
//  Demo
//
//  Created by RYAN on 15/6/17.
//
//

#import "BSLGalleryPlugin.h"
#import "BSLAlbumsTableViewController.h"
#import "AppDelegate.h"

#import "CDVCamera.h"

@implementation GalleryNavigationController

- (void)dismiss:(NSMutableArray *)paths errorMessage:(NSString *)message{
    
    __weak GalleryNavigationController *weakSelf = self;
    [self dismissViewControllerAnimated:[BSLGalleryHelper shareInatance].isAnimated completion:^{
        
        CDVPluginResult *pluginResult;
        if (!paths || paths.count ==0) {
            pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:((message) ? message : @"error but no prompt")];
        }
        
        else{
//            if (paths.count == 1){//单选
//                NSString *path = [paths firstObject];
//                pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:path];
//            }
//            
//            else{
//                pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray:paths];
//            }
            pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsArray:paths];
        }
        
        [weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:weakSelf.callbackID];
        
    }];
}

@end

@interface BSLGalleryPlugin ()

@property (nonatomic, strong) CDVCamera *cameraPlugin;

@end

@implementation BSLGalleryPlugin

- (void)pick:(CDVInvokedUrlCommand*)command{
    
    __weak BSLGalleryPlugin *weakSelf = self;
    [self.commandDelegate runInBackground:^{
        
        NSString *callbackID = command.callbackId;
        BSLGalleryHelper *helper = [BSLGalleryHelper shareInatance];
        [helper setPropertyWithCommand:command];

        if (helper.shouldMultiple) {
            //多选
            BSLAlbumsTableViewController *bslAlbumsTableViewController = [[BSLAlbumsTableViewController alloc] initWithStyle:UITableViewStylePlain];
            AppDelegate *appDelegate = (AppDelegate *)([UIApplication sharedApplication].delegate);
            
            GalleryNavigationController *navC = [[GalleryNavigationController alloc] initWithRootViewController:bslAlbumsTableViewController];
            navC.callbackID = callbackID;
            navC.commandDelegate = self.commandDelegate;
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                if ([helper popoverSupported]) {
                    //ipad下可以指定界面位置
                    CGRect frame = [helper getPoppverControllerFrame];
                    UIPopoverController *pop = [[UIPopoverController alloc] initWithContentViewController:navC];
                    CGRect view_Frame = SCREEN_FRAME;
                    pop.popoverContentSize = view_Frame.size;
                    UIViewController *rootVC = [navC viewControllers][0];
                    [rootVC.view setFrame:view_Frame];
                    
                    weakSelf.popoverController = pop;
                    [pop presentPopoverFromRect:frame inView:weakSelf.webView permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
                }
                
                else{
                    [appDelegate.window.rootViewController presentViewController:navC animated:helper.isAnimated completion:^{
                        
                    }];
                }
                
            });
        }
        
        else{
            id popoverOptions = (!helper.popoverOptions) ? [NSNull null] : helper.popoverOptions;
            //单选 使用camera插件打开
            NSArray *args = @[@50,@1,@0,@(-1),@(-1),@(0),@(0),@(0),@(0),@(0),popoverOptions,@(0)];
            CDVInvokedUrlCommand *command2 = [[CDVInvokedUrlCommand alloc] initWithArguments:args callbackId:command.callbackId className:@"CDVCamera" methodName:@"takePicture"];
            if (!weakSelf.cameraPlugin) {
                
                CDVCamera *cameraPlugin = [[CDVCamera alloc] initWithWebView:weakSelf.webView];
                cameraPlugin.commandDelegate = weakSelf.commandDelegate;
                cameraPlugin.viewController = weakSelf.viewController;
                weakSelf.cameraPlugin = cameraPlugin;
            }
            
            [weakSelf.cameraPlugin takePicture:command2];
        }
        
    }];
}

- (void)save:(CDVInvokedUrlCommand*)command{
    
    [self.commandDelegate runInBackground:^{
        
        self.callbackID = command.callbackId;
        NSString *path = command.arguments[0];
        UIImage *img = [UIImage imageWithContentsOfFile:path];
        UIImageWriteToSavedPhotosAlbum(img, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
    }];
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(NSString *)contextInfo{
    
    CDVPluginResult *result = nil;
    if (error == nil) {
        result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
    }
    
    else{
        result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsInt:(int)error.code];
    }
    
    [self.commandDelegate sendPluginResult:result callbackId:self.callbackID];
}

@end
